# _*_ coding:utf-8 _*_
# @File  : article.py
# @Time  : 2022-01-18  13:24
# @Author: zizle

from fastapi import APIRouter, Query, Body
from pydantic import BaseModel

from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils
from db import FAConnection

article_api = APIRouter()


class QhrbArticleItem(BaseModel):
    create_time: str
    raw_time: str
    title: str
    authors: str
    words: str
    issue_num: str
    layout: int
    is_special: int
    content: str


@article_api.post('/')  # 上传期货日报文章
def save_qhrb_article(article: QhrbArticleItem = Body(...)):
    create_time = datetime_utils.auth_datetime_string(article.create_time, f='%Y-%m-%d %H:%M:%S')
    raw_time = datetime_utils.auth_datetime_string(article.raw_time, f='%Y-%m-%d %H:%M:%S')
    if not all([create_time, raw_time]):
        return AllResponse.validate_error(msg='日期无法格式化为`%Y-%m-%d %H:%M:%S`')
    create_sql = 'INSERT INTO qhrb_article (create_time,raw_time,title,authors,words,issue_num,layout,is_special,' \
                 'content) ' \
                 'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);'
    params = [create_time, raw_time, article.title, article.authors, article.words, article.issue_num, article.layout,
              article.is_special, article.content]
    db_conn = FAConnection(conn_name='添加期货日报文章')
    success, _ = db_conn.insert(create_sql, params)
    return AllResponse.create_successfully() if success else AllResponse.server_error()


@article_api.get('/')  # 查询获取期货日报文章
def qhrb_article(issue: int = Query(None), authors: str = Query(None), title: str = Query(None),
                 date: str = Query(None), page: int = Query(1, ge=1), page_size: int = Query(10, ge=1)):
    issue = issue if issue else '0'
    authors = authors if authors else '0'
    title = title if title else '0'
    query_date = datetime_utils.auth_datetime_string(datetime_string=date, f='%Y-%m-%d') if date else '0'
    start, offset = (page - 1) * page_size, page_size

    db_conn = FAConnection()
    if all([issue == '0', authors == '0', title == '0', query_date != '0']):
        sql = """
            SELECT id,create_time,raw_time,title,authors,words,issue_num,layout,is_special,content 
            FROM qhrb_article 
            WHERE create_time=%s;
        """
        prm = [query_date + ' 00:00:00']
        records = db_conn.query(sql, prm)
        ret = {
            'records': records,
            'total_count': len(records),
            'total_page': 1,
            'cur_page': 1,
            'page_size': len(records)
        }
    else:
        sql = """
            SELECT SQL_CALC_FOUND_ROWS id,create_time,raw_time,title,authors,words,issue_num,layout,is_special,content 
            FROM qhrb_article WHERE 
            IF(%s="0",TRUE,issue_num=%s) AND 
            IF(%s="0",TRUE,authors LIKE %s) AND 
            IF(%s="0",TRUE,title LIKE %s) AND 
            IF(%s="0",TRUE,DATE_FORMAT(create_time,"%%Y-%%m-%%d")=%s) 
            ORDER BY create_time DESC LIMIT %s,%s;
        """
        params = [issue, issue, authors, f'%{authors}%', title, f'%{title}%', query_date, query_date, start, offset]
        ret = db_conn.paginator_query(sql=sql, param=params, page=page, page_size=page_size)
        ret['page_size'] = page_size
    for atle in ret['records']:
        atle['create_time'] = atle['create_time'].strftime('%Y-%m-%d')
        atle['raw_time'] = atle['raw_time'].strftime('%Y-%m-%d %H:%M:%S')
    return AllResponse.operate_successfully(data=ret)
